from datetime import datetime
import talib as ta
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import time
import redis
from math import *
import traceback
from vnpy.trader.constant import Exchange, Interval
from vnpy.trader.object import HistoryRequest, LogData
from vnpy.trader.rqdata import rqdata_client
from vnpy.trader.database import database_manager
from vnpy.trader.ui import create_qapp, QtCore

def handle_close(evt):
    print("Closed Figure!")
    exit(0)

FLAT_NUM= 60
SMA_NUM= 30

if __name__ == "__main__":
    
    symbol = "IF2201"
    exchange = Exchange.CFFEX
    start = datetime(2021, 12, 1)
    end = datetime(2022, 3, 17)
    interval = Interval.MINUTE
    bars = database_manager.load_bar_data(
        symbol, Exchange.CFFEX, interval=Interval.MINUTE, start=start, end=end
    )
    if not bars or len(bars) == 0:
        req = HistoryRequest(
            symbol=symbol,
            exchange=exchange,
            interval=Interval.MINUTE,
            start=start,
            end=end,
        )
        try:
            bars = rqdata_client.query_history(req)

            if bars:
                database_manager.save_bar_data(bars)
                print(f"{symbol}-{interval}历史数据下载完成")
            else:
                print(f"数据下载失败，无法获取{symbol}的历史数据")
        except Exception:
            msg = f"数据下载失败，触发异常：\n{traceback.format_exc()}"
            print(msg)


    fig = plt.figure()
    fig.canvas.mpl_connect("close_event", handle_close)

    df = pd.DataFrame(
        [
            {
                "Close": s.close_price,
                "Low": s.low_price,
                "High": s.high_price,
                "Open": s.open_price,
                "Volume": s.volume,
            }
            for s in bars
        ]
    )
    df['macd','macdsignal','macdhist'] = ta.MACD(bars['close_price'].values, fastperiod=12, slowperiod=26, signalperiod=9)
    plt.plot(df.index, df[["Close2",  "macd",'macdsignal','macdhist']])
    plt.legend(["Close2",  "macd",'macdsignal','macdhist'])

    plt.show()
